<?php


class Stock extends BaseBean{

    public $def_state=STOCK_NEW;
    public $stock_type="";
    public $_table= "tb_stock_master";
    public $_primarykey= "id";
    public $_table_alias= "a";
    public $_mustFields =array("bill_date"=>"单据日期","stock_type"=>"单据类型");
    public $_audit_flag =0;

    public function __construct(){
        $this->addChild("StockDetail","id","master_id");
    }

    public function generateSql(){
        return "select a.*,c.name as create_user,b.name as supply,f.name as shop,e.name as target_shop 
                    from tb_stock_master a left join tb_supply b on a.supply_id=b.id
                        left join tb_users c on c.id = a.create_user_id
                        left join tb_shop e on a.target_shop_id = e.id
                        left join tb_shop f on a.shop_id = f.id";
    }

   

    public function save(){
        $amount =0;
        $state = $this->get("state");
        if($state == null || $state == ""){
            $state = $this->def_state;
        }
        $detailList = $this->getChildBeanList("StockDetail",false);
        $this->set("stock_type",$this->stock_type);
        $this->set("state",$state);         
        if($detailList!=null){
            for($i=0;$i<count($detailList);$i++){
                $detailList[$i]->set("stock_type",$this->stock_type);
                $detailList[$i]->set("factor",$this->factor);
                $detailList[$i]->set("state",$state);         

                if($detailList[$i]->get(DATA_ROW_STATE)!=4){
                    $amount += $detailList[$i]->amount;
                }
            }
            $this->set("amount",$amount);
        }
        if($this->get("create_date") == null){
            $this->set("create_date",date('Y-m-d',time()));
        }

         if($this->get("create_user_id") == null){
            $this->set("create_user_id",Users::GetLoginUserID());
        }

        if($this->get("create_dept_id") == null){
            $this->set("create_dept_id",Users::GetLoginShopID());
        }

        if($this->get("company_id") == null){
            $this->set("company_id",Users::GetLoginCommpanyID());
        }
        parent::save();
    }


    public function switchState($state){
    
        $this->set("state",$state);
        $detailList = $this->getChildBeanList("StockDetail",false);
        if($detailList == null || count($detailList) ==0){
            $this->loadChildren();
        }
        parent::save();
    }

    public function audit(){
        $this->switchState(FINISHED);
    }
    

  
}
?>